﻿using GComp.Apps.EasyStock.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using Windows.Storage.Streams;

namespace GComp.Apps.EasyStock.DataModel.Search {
    public class SymbolListManager {
        private const string URL_NASDAQ = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter={0}&render=download";
        private const string FILE_URL = "Symbols_Letter_{0}.txt";

        public BackgroundWorkState WorkState { get; set; }

        public async void DownloadAll() {
            for (char letter = 'A'; letter <= 'Z'; letter++) {
                string fullUrl = string.Format(URL_NASDAQ, letter);
                string filename = string.Format(FILE_URL, letter);

                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                //if the folder already exists, the method does nothing
                StorageFolder folder = await localFolder.CreateFolderAsync("symbols", CreationCollisionOption.OpenIfExists);

                bool fileExists;
                try {
                    StorageFile existingFile = await folder.GetFileAsync(filename);
                    fileExists = true;
                } catch (FileNotFoundException) {
                    fileExists = false;
                }

                if (fileExists) {
                    Debug.WriteLine("File " + letter + " does exist, so do nothing");
                    WorkState.Downloaded++;
                    //file does exist, so do nothing
                    continue;
                }

                StorageFile sf = await folder.CreateFileAsync(filename);

                BackgroundDownloader downloader = new BackgroundDownloader();
                Debug.WriteLine("Starting download " + letter);
                DownloadOperation operation = downloader.CreateDownload(new Uri(fullUrl), sf);
                bool hasStarted = operation.Progress.HasRestarted;
                Debug.WriteLine("HasStarted: " + hasStarted);
                await operation.StartAsync();
                operation.AttachAsync().Completed = OnCompleted;
            }
        }

        private void OnCompleted(IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> asyncInfo, AsyncStatus asyncStatus) {
            Debug.WriteLine("Finished download");
            WorkState.Downloaded++;
        }

        internal async Task<List<StockEntry>> Search(string searchPattern) {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            //if the folder already exists, the method does nothing
            StorageFolder folder = await localFolder.CreateFolderAsync("symbols", CreationCollisionOption.OpenIfExists);
            IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();

            List<StockEntry> entries = new List<StockEntry>();

            foreach (StorageFile file in files) {
                string s = await FileIO.ReadTextAsync(file);

                MatchCollection matches = Regex.Matches(s, "^\"([^\"]*)\",\"([^\"]*?(" + searchPattern + ")[^\"]*?)\"", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                foreach (Match match in matches) {
                    string symbol = match.Groups[1].Value;
                    string name = match.Groups[2].Value;
                    entries.Add(new StockEntry {
                        Symbol = symbol,
                        Name = name
                    });
                }
            }
            return entries;
        }
    }
}
